package com.web;

import com.bean.Phone;
import com.dao.PhoneDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Date;

@WebServlet("/phone/update")
public class PhoneUpdateServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");

        try {
            Phone phone = new PhoneDao().get(Integer.parseInt(id));
            req.setAttribute("phone", phone);
            req.getRequestDispatcher("/phone/phoneUpdate.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("message", "单条信息查询失败！" + e.getLocalizedMessage());
            req.getRequestDispatcher("/phone/message.jsp").forward(req, resp);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String price = req.getParameter("price");
        String model = req.getParameter("model");
        String color = req.getParameter("color");
        String origin = req.getParameter("origin");
        Date time = Date.valueOf(req.getParameter("time"));

        try {
            new PhoneDao().update(Integer.parseInt(id), name, Float.parseFloat(price), model, color, origin, time);
            req.setAttribute("message","更新成功");
            req.getRequestDispatcher("/phone/message.jsp").forward(req, resp);
        } catch (Exception e) {
            e.printStackTrace();
            req.setAttribute("message", "更新失败！" + e.getLocalizedMessage());
            req.getRequestDispatcher("/phone/message.jsp").forward(req, resp);
        }
    }
}
